package com.fellansoft.moviescollection.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.*;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.fellansoft.moviescollection.R;
import com.fellansoft.moviescollection.business.BusinessConstants;
import com.fellansoft.moviescollection.business.DataManager;
import com.fellansoft.moviescollection.utils.ActivityUtils;
import com.fellansoft.moviescollection.utils.ApplicationVariables;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by IntelliJ IDEA.
 * User: Naty       ->naty
 * Date: 5/11/12
 * Time: 10:10 PM
 * To change this template use File | Settings | File Templates.
 */

public class AddMovie extends Activity {

    /**
     * The application context used to register receivers
     */
    private Context context;

    /**
     * Intent filter for the intents sent when the book was saved successfully
     */
    private IntentFilter saveMovieSuccessIntentFilter;

    /**
     * Intent filter for the intents sent when the book was not saved successfully
     */
    private IntentFilter saveMovieErrorIntentFilter;

    /**
     * Receiver for the intents sent when the book was saved successfully to database
     */
    private BroadcastReceiver saveMovieSuccessReceiver;

    /**
     * Receiver for the intents sent when there was a problem saving the new book to database
     */
    private BroadcastReceiver saveMovieErrorReceiver;

    /**
     * Intent filter for the intents sent when the movies were received from database
     */
    private IntentFilter receiveMoviesSuccessIntentFilter;

    /**
     * Intent filter for the intents sent when the movies were not received from the database
     */
    private IntentFilter receiveMoviesErrorIntentFilter;

    /**
     * Receiver for the intents sent when the movies were received from the database
     */
    private BroadcastReceiver receiveMoviesSuccessReceiver;

    /**
     * Receiver for the intents sent when the movies were not received from the database
     */
    private BroadcastReceiver receiveMoviesErrorReceiver;
    /**
     *      Intent filter for the intents sent when the movies were retrieved from the database by id with success
     */

    private IntentFilter getMovieByIdSuccessIntentFilter=null;
    /**
     *      Receiver for the  intents sent when the movies were retrieved from the database by id with success
     */
    private BroadcastReceiver getMovieByIdSuccessReceiver=null;
    /**
     *      Intent filter for the intents sent when the movies were retrieved from the database by id which failed
     */
    private IntentFilter getMovieByIdErrorIntentFilter=null;
    /**
     *      Receiver for the intents sent when the movies were retrieved from the database by id which failed
     */
    private BroadcastReceiver getMovieByIdErrorReceiver=null;

    /**
     * Edit Text where the title will be written
     */
    private EditText titleEditText;

    /**
     * Edit Text where the description date will be written
     */
    private EditText descriptionEditText;

    /**
     *  Button to start date picker
     */
    private Button selectDateButton;
    /**
     * Edit Text where the selected date will be displayed 
     */
    private EditText dateEditText;
    /**
     *  Constant for starting a dialog with a date picker
     */
    static final int DATE_DIALOG_ID = 999;
    /**
     * Integer for storing the current year
     */
    private int year=2000;
    /**
     * Integer for storing the current month
     */
    private int month=1;
    /**
     * Integer for storing the current day
     */
    private int day=1;
    /**
     * Button for the select categories dialog
     */
    private Button selectCategoriesButton;
    /**
     *  Value for Date Picker Dialog
     */
    static final int CATEG_DIALOG_ID = 666;

    /**
     * Value for Activity Result
     */

    final int SELECT_PHOTO = 1;
    /**
     * Sequence of categories
     */

    protected CharSequence[] categories;
    /**
     * Boolean values for the selected categories
     */
    protected boolean[] categoriesSelection;
    /**
     * Checkbox for movie being marked for watch list
     */
    private CheckBox watchlistCheckbox;
    /**
     * Checkbox for movie being favorited
     */
    private CheckBox favouriteCheckbox;
    /**
     * Checkbar loaded with a float value
     */
    private RatingBar ratingBar;
    /**
     * Button for managing pictures
     */
    private Button addPictureButton;
    /**
     * Button for saving the current state of a movie
     */

    private Button saveButton;
    /**
     * Cancel adding a new movie
     */
    private Button cancelButton;
    /**
     * Flag used for checking if the list of pictures was initialized before
     */
    private boolean picturesListInitializedFlag = false;

    private boolean flag;

    private boolean isNotEmptyCategories (boolean[] x) {

        for (boolean i : x) {
            if (i)
                return true;
        }
        return false;
    }
    
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setTheme(android.R.style.Theme_Holo);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.addmovie);

        context = ApplicationVariables.getApplicationContext();

        if (picturesListInitializedFlag == false)
        {
            PictureControl.uriList = new ArrayList<Uri>();
            picturesListInitializedFlag = true;
        }

        categories = getResources().getStringArray(R.array.Categories);

        categoriesSelection = new boolean[categories.length ];

        titleEditText=(EditText)findViewById(R.id.addTitleEditText);

        watchlistCheckbox=(CheckBox)findViewById(R.id.watchCheckB);

        favouriteCheckbox=(CheckBox)findViewById(R.id.favoriteCheckB);

        descriptionEditText=(EditText)findViewById(R.id.addDescription);

        dateEditText=(EditText)findViewById(R.id.dateEditText);

        // get the current date
        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        selectDateButton=(Button)findViewById(R.id.datePickerButton);
        selectDateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        //multi selection dialog
        selectCategoriesButton=(Button)findViewById(R.id.selectCategory);
        selectCategoriesButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                showDialog(CATEG_DIALOG_ID);
            }
        });

        ratingBar=(RatingBar)findViewById(R.id.rating);
        /*ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                Toast.makeText(getApplicationContext(), ""+ratingBar.getRating(), Toast.LENGTH_LONG).show();
            }
        });   */

        addPictureButton=(Button)findViewById(R.id.managePictures);
        addPictureButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                //DataManager.getInstance().getMovieById(Long.valueOf(1));
                Intent intent=new Intent(AddMovie.this,PictureControl.class);
                intent.putExtra("ADDMOVIE",1);
                startActivity(intent);
                //Intent intent=new Intent(AddMovie.this,ViewMovie.class);
                //startActivity(intent);
            }
        });

        saveButton=(Button)findViewById(R.id.saveMovieButton);
        saveButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                //Register the receivers
                if (saveMovieSuccessIntentFilter == null)
                    saveMovieSuccessIntentFilter = new IntentFilter(BusinessConstants.BC_MOVIE_SAVED_SUCCESSFULLY);
                if (saveMovieSuccessReceiver == null)
                    saveMovieSuccessReceiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context localContext, Intent intent) {
                            try {
                                context.unregisterReceiver(saveMovieSuccessReceiver);
                            } catch(IllegalArgumentException e) {
                                e.printStackTrace();
                            }

                            //Show a message on the screen
                            Toast.makeText(AddMovie.this,AddMovie.this.getResources().getString(R.string.save_success_message),Toast.LENGTH_SHORT).show();
                            AddMovie.this.setResult(Activity.RESULT_OK);
                            finish();
                        }
                    };
                context.registerReceiver(saveMovieSuccessReceiver, saveMovieSuccessIntentFilter);

                if (saveMovieErrorIntentFilter == null)
                    saveMovieErrorIntentFilter = new IntentFilter(BusinessConstants.BC_MOVIE_SAVED_ERROR);
                if (saveMovieErrorReceiver == null)
                    saveMovieErrorReceiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context localContext, Intent intent) {
                            try {
                                context.unregisterReceiver(saveMovieErrorReceiver);
                            } catch(IllegalArgumentException e) {
                                e.printStackTrace();
                            }
                             //Hide the spinning dialog
                            ActivityUtils.hideProgressDialog(AddMovie.this);

                            //Show a message on the screen
                            Toast.makeText(AddMovie.this,AddMovie.this.getResources().getString(R.string.save_error_message),Toast.LENGTH_SHORT).show();
                        }
                    };
                context.registerReceiver(saveMovieErrorReceiver,saveMovieErrorIntentFilter);

                AlertDialog alertDialog;
                AlertDialog.Builder builder;
                flag = true;

               //NO TITLE
               if (titleEditText.getText().toString().equals("")) {
                   flag = false;

                   builder = new AlertDialog.Builder(AddMovie.this);
                   builder.setMessage("Movie title is required!")
                         .setTitle("ERROR")
                         .setCancelable(false)
                         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                        return;
                                }
                         });

                   alertDialog = builder.create();
                   alertDialog.show();
               }


               //AT LEAST ONE PHOTO
               if (PictureControl.getPhotos().size() == 0 && flag) {
                   flag = false;

                   builder = new AlertDialog.Builder(AddMovie.this);
                   builder.setMessage("At least one picture is required!")
                         .setTitle("ERROR")
                         .setCancelable(false)
                         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                        return;
                                }
                         });

                   alertDialog = builder.create();
                   alertDialog.show();
               }

               //AT LEAST ONE CATEGORY
               if (isNotEmptyCategories(categoriesSelection) == false && flag) {
                   flag = false;

                   builder = new AlertDialog.Builder(AddMovie.this);
                   builder.setMessage("At least one category is required")
                         .setTitle("ERROR")
                         .setCancelable(false)
                         .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                        return;
                                }
                         });

                   alertDialog = builder.create();
                   alertDialog.show();
               }


                try {
                    if(flag) {
                        //Show the progress dialog
                        ActivityUtils.showProgressDialog(AddMovie.this);

                        DataManager.getInstance().requestSaveMovie(
                                titleEditText.getText().toString(), // title
                                dateEditText.getText().length() == 0 ? null : DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).parse(dateEditText.getText().toString()), //releaseDate
                                descriptionEditText.getText().toString(), //description
                                "", // director
                                categoriesSelection, // categories
                                watchlistCheckbox.isChecked(), //watchlist
                                favouriteCheckbox.isChecked(), //favourite
                                ratingBar.getRating(), //ownRating
                                PictureControl.getPhotos().get(0),
                                PictureControl.getPhotos());
                        picturesListInitializedFlag = false;
                        //finish();

                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });

        cancelButton=(Button)findViewById(R.id.cancelButton);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                finish();
            }
        });
    }

    public void onPause()
    {
        super.onPause();
        if (saveMovieSuccessReceiver != null)
        {
            try{
                this.unregisterReceiver(saveMovieSuccessReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            saveMovieSuccessReceiver = null;
        }
    }

   /* public Movie getMovieById(Long movieID)
    {
        if (getMovieByIdSuccessIntentFilter == null)
            getMovieByIdSuccessIntentFilter = new IntentFilter(ViewConstants.VIEW_MOVIE_GETBYID_SUCCESSFULLY);
        if (getMovieByIdSuccessReceiver == null)
            getMovieByIdSuccessReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(getMovieByIdSuccessReceiver);
                    Movie movie= DatabaseHelper.getInstance().getMovie();
                    Log.d("MOVIETITLE",movie.getTitle());
                    //Notify the success to Activity
                   // ApplicationVariables.getApplicationContext().sendBroadcast(new Intent());
                }
            };
        context.registerReceiver(getMovieByIdSuccessReceiver, getMovieByIdSuccessIntentFilter);

        if (getMovieByIdErrorIntentFilter == null)
            getMovieByIdErrorIntentFilter = new IntentFilter(ViewConstants.VIEW_MOVIE_GETBYID_ERROR);
        if (getMovieByIdErrorReceiver == null)
            getMovieByIdErrorReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context localContext, Intent intent) {
                    context.unregisterReceiver(getMovieByIdErrorReceiver);

                    //Notify the success to Activity
                    ApplicationVariables.getApplicationContext().sendBroadcast(new Intent(PersistenceConstants.PC_MOVIE_GETBYID_ERROR));
                }
            };
        context.registerReceiver(getMovieByIdErrorReceiver, getMovieByIdErrorIntentFilter);


        //Make the request
        DataManager.getInstance().getMovieById(movieID);
        //DatabaseHelper.getInstance().getMovieById(movieID);

        return null;
        //
    }      */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID:
                //creates the DatePicker with the datePickerListener and initial values: year,month,date
                return new DatePickerDialog(this, datePickerListener, year, month, day);
            case CATEG_DIALOG_ID:
                //creates the DatePicker with the datePickerListener and initial values: year,month,date
                return
                        new AlertDialog.Builder( this )
                                .setTitle( R.string.categories )
                                .setMultiChoiceItems( categories, categoriesSelection , new DialogSelectionClickHandler() )
                                .setPositiveButton( R.string.save, new DialogButtonClickHandler() )
                                .create();
        }
        return null;
    }

    // Listener for Date Picker
    private DatePickerDialog.OnDateSetListener datePickerListener
            = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {
            Date d = new Date(selectedYear-1900,selectedMonth,selectedDay);
            dateEditText.setText(DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(d));

          // set selected date into datepicker also
          //  dpResult.init(year, month, day, null);
        }
    };

    public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener
    {
        public void onClick( DialogInterface dialog, int clicked, boolean selected )
        {

            //change is made in the list

            /*public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            if(isChecked)
                selectedColours.add(colours[which]);
            else
                selectedColours.remove(colours[which]);

            onChangeSelectedColours();
        }      */
        }

    }


    public class DialogButtonClickHandler implements DialogInterface.OnClickListener
    {
        public void onClick( DialogInterface dialog, int clicked )
        {
            switch( clicked )
            {
                case DialogInterface.BUTTON_POSITIVE:
                    //nothing to do
                    //Toast.makeText(getApplicationContext(),categoriesSelection[0]==true?"true":"false",Toast.LENGTH_SHORT).show();
                    //categoriesSelection = ((AlertDialog)dialog).getListView().;
                    //printSelectedCategories();
                    break;
            }
        }
    }
     /*
    protected void printSelectedCategories(){
        StringBuilder result=new StringBuilder();
        for( int i = 0; i < categoriesSelection.length; i++ ){
            if(categoriesSelection[i]==true)
                result.append(categories[i] + " ");

        }
        Log.d("Result ",result.toString());
    }   */

   /*
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch(requestCode) {
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK){
                Uri selectedImage = imageReturnedIntent.getData();
                InputStream imageStream=null;
                try {

                imageStream = getContentResolver().openInputStream(selectedImage);
                } catch (FileNotFoundException e) {
                    // Auto-generated catch block
                    e.printStackTrace();
            }
                //Toast.makeText(this,selectedImage.toString(),Toast.LENGTH_SHORT).show();
            //Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
            //image.setImageBitmap(yourSelectedImage);
        }
    }
    }  */

}
